<?php

namespace app\web\controller;

use app\admin\model\AdminLog;
use app\common\controller\Frontend;
use app\common\model\customer\Customer as customerModel;
use think\Config;
use think\Db;
use think\Hook;
use think\Validate;

class Users extends Frontend
{

    protected $noNeedLogin = 'login';
    protected $noNeedRight = '*';
    protected $layout = '';
    public function _initialize()
    {
        parent::_initialize();
    }

   public function index(){
       $this->assign('purl','users');
       $this->assign('admin',session('admin'));
       return $this->view->fetch();
   }
   public function login(){
        if(session('user_id')){
            $rr =Db::name('user_binding')->where(array(
                'user_id'=>session('user_id'),
                'is_default'=>1,
            ))->find();
            if($rr){
                session('admin',Db::name('admin')->where(array('id'=>$rr['admin_id']))->find());

                $this->redirect(session('url'));
                exit;
            }
        }else{
            session('url',$this->request->url());
            $this->error(__('Please login first'), 'web/wweixin/getcode');
        }


       $url = $this->request->get('url', 'index/index');
       if ($this->auth->isLogin()) {
           $this->success(__("You've logged in, do not login again"), $url);
       }
       if ($this->request->isPost()) {
           $username = $this->request->post('username');
           $password = $this->request->post('password');
           $token = $this->request->post('token');
           $rule = [
               'username'  => 'require|length:3,30',
               'password'  => 'require|length:3,30',
               '__token__' => 'require|token',
           ];
           $data = [
               'username'  => $username,
               'password'  => $password,
               '__token__' => $token,
           ];
           if (Config::get('fastadmin.login_captcha')) {
               $rule['captcha'] = 'require|captcha';
               $data['captcha'] = $this->request->post('captcha');
           }
           $validate = new Validate($rule, [], ['username' => __('Username'), 'password' => __('Password'), 'captcha' => __('Captcha')]);
           $result = $validate->check($data);
           if (!$result) {
               $this->error($validate->getError(), $url, ['token' => $this->request->token()]);
           }
           AdminLog::setTitle(__('Login'));

           $result = $this->auth->loginadmin($username, $password, 86400 ? 86400 : 0);
           if ($result === true) {
               $rr =Db::name('user_binding')->where(array(
                   'user_id'=>session('user_id'),
                   'admin_id'=>session('admin')['id'],
               ))->find();
               if(!$rr){
                   Db::name('user_binding')->insert(array(
                       'user_id'=>session('user_id'),
                       'admin_id'=>session('admin')['id'],
                       'is_default'=>1,
                   ));
               }
               Hook::listen("admin_login_after", $this->request);
               $this->success(__('登录成功'), $url, ['url' => $url, 'id' => $this->auth->id, 'username' => $username, 'avatar' => $this->auth->avatar]);
           } else {
               $msg = $this->auth->getError();
               $msg = $msg ? $msg : __('Username or password is incorrect');
               $this->error($msg, $url, ['token' => $this->request->token()]);
           }
       }


       $background = Config::get('fastadmin.login_background');
       $background = stripos($background, 'http') === 0 ? $background : config('site.cdnurl') . $background;
       $this->view->assign('background', $background);
       $this->view->assign('title', __('Login'));
       Hook::listen("admin_login_init", $this->request);
//       if()
       return $this->view->fetch();
   }
   public function forget(){

   }
   public function setting(){
       return $this->view->fetch();
   }
   public function setinfo(){
       return $this->view->fetch();
   }
   public function logout(){
        session(null);
        $this->success('退出成功');
   }
   //角色管理
   public function roles(){
       $users = Db::name('user_binding')
           ->alias('u')
           ->where(array('user_id'=>session('user_id')))
           ->join('admin a','u.admin_id = a.id')
           ->select();
       $this->assign('users',$users);
       return $this->view->fetch();
   }
   //角色切换
   public function userswitch(){
        $admin_id = input('admin_id/d',0);
        if(session('admin')['id'] == $admin_id){
           return array(
             'code'=>2,
             'message'=>'无需切换',
           );
        }
        $row = Db::name('user_binding')->where(array('user_id'=>session('user_id'),'admin_id'=>$admin_id))->find();
        if(empty($row)){
            $this->error('切换失败');
        }
       Db::name('user_binding')->where(array('user_id'=>session('user_id')))->update(array('is_default'=>0));
       Db::name('user_binding')->where(array('user_id'=>session('user_id'),'admin_id'=>$admin_id))->update(array('is_default'=>1));
        //重置session
        $arow = Db::name('admin')->where(array('id'=>$admin_id))->find();
        session('admin',$arow);
        $this->success('切换成功');
    }
   //添加绑定
   public function addbinding(){
        $nickname = input('nickname');
        $password = input('password');
        $row = Db::name('admin')->where(array(
            'username'=>$nickname,
//            'password'=>$password,
        ))->find();


        if(empty($row)){
            $this->error('查无此号');
        }else{
            if ($row['password'] != md5(md5($password) . $row['salt'])) {
                $this->error('密码错误');
            }
            $rr =Db::name('user_binding')->where(array(
                'user_id'=>session('user_id'),
                'admin_id'=>$row['id'],
            ))->find();
            if($rr){
                $this->error('已绑定');
            }
            $res = Db::name('user_binding')->insert(array(
               'user_id'=>session('user_id'),
               'admin_id'=>$row['id'],
            ));
            if($res){
                $this->success('添加成功');
            }
            $this->error('添加失败');
        }
   }
}
